<template>
  <div class="bg-white">
    <div class="pt-4">
      <div class="grid gap-4" style="grid-template-columns: repeat(auto-fill, 300px)">
        <div
          v-for="item in modelValue"
          :key="item.tenantId"
          class="flex items-center p-2 rounded-lg bg-[#F2F3F5]"
        >
          <div class="flex-shrink-0">
            <Avatar :src="item.orgLogo" shape="square" :size="48" />
          </div>

          <div class="pl-2 line-clamp-2 w-full">{{ item.orgName }}</div>
          <div class="p-3 pr-1 flex-shrink-0" @click="handRemove(item)">
            <Icon icon="ant-design:close" />
          </div>
        </div>
      </div>
      <div class="py-4">
        <Button type="primary" ghost @click="openSelectModal">
          <Icon icon="ant-design:plus" />
          添加可见组织
        </Button>
      </div>
    </div>

    <SelectOrganization
      @register="registerOrganization"
      @ok="configSelect"
      :bo-info-id="boInfoId"
    />
  </div>
</template>
<script lang="ts" setup>
  import { Button, Avatar } from 'ant-design-vue';
  import { Icon } from '@/components/Icon';
  import SelectOrganization from './selectOrganization.vue';
  import { useModal } from '@/components/Modal';
  import { MerchantListType } from '@/enums/resourceLeague';
  import { IOrgList } from '@/api/institution/model/businessOpportunitiesManageModel';

  const props = defineProps({
    modelValue: {
      type: Array as PropType<IOrgList[]>,
      default: () => [],
    },
    boInfoId: {
      type: Number,
    },
  });
  const emit = defineEmits(['update:modelValue']);

  // 从列表移除组织
  const handRemove = (item) => {
    const filterList = props.modelValue.filter((v) => v.tenantId !== item.tenantId);
    emit('update:modelValue', filterList);
  };

  // 打开选择组织弹窗
  const [registerOrganization, { openModal }] = useModal();
  const openSelectModal = () => {
    openModal(true, {
      type: MerchantListType.PRODUCTLIBRARY,
      disabledIds: props.modelValue.map((v) => v.tenantId) as number[],
    });
  };

  const configSelect = (selectedList) => {
    let dataList = selectedList.map((v) => {
      return {
        orgLogo: v.orgLogo,
        orgName: v.orgName,
        tenantId: v.tenantId,
        id: v?.id ?? undefined,
      };
    });
    emit('update:modelValue', [...props.modelValue, ...dataList]);
  };
</script>

<style lang="less" scoped></style>
